import matplotlib.pyplot as plt
import csv
import numpy as np
f = open('ds/namesex_data_v2.csv', 'r', encoding='utf8')
mydata = csv.DictReader(f)
sexlist = []
namelist = []
foldlist = []
for i, arow in enumerate(mydata):
if i < 10:
print(arow)
sexlist.append(int(arow['sex'].strip()))
gname = arow['gname'].strip()
namelist.append(gname)
foldlist.append(int(arow['fold'].strip()))
sexlist = np.asarray(sexlist)
namelist = np.asarray(namelist)
foldlist = np.asarray(foldlist)
f.close()
{'gname': '承憲', 'sex': '1', 'fold': '9'}
{'gname': '均平', 'sex': '1', 'fold': '7'}
{'gname': '思安', 'sex': '0', 'fold': '6'}
{'gname': '佑誠', 'sex': '1', 'fold': '3'}
{'gname': '乃馨', 'sex': '0', 'fold': '0'}
{'gname': '婕', 'sex': '0', 'fold': '0'}
{'gname': '冠瑜', 'sex': '0', 'fold': '1'}
{'gname': '冠學', 'sex': '1', 'fold': '0'}
{'gname': '立翰', 'sex': '1', 'fold': '2'}
{'gname': '以柔', 'sex': '0', 'fold': '6'}
import pandas as pd
name_df = pd.DataFrame({'sex': sexlist, 'name': namelist, 'fold': foldlist})
print(name_df)
sex_tend = name_df[['name', 'sex']].groupby(["name"]).agg(['mean', 'count']).reset_index()
sex_tend.columns = ['-'.join(col).strip() for col in sex_tend.columns.values]
sex_tend = sex_tend.sort_values(['sex-count'], ascending=False)
sex_tend.head(20)
nobs = namelist.shape[0] #資料筆數
avg_sex = np.mean(sexlist)
single_name = np.sum(sex_tend['sex-count'] <= 1)
ind1 = (sex_tend['sex-mean'] > 0.4) & (sex_tend['sex-mean'] < 0.6)
sex_amb = sex_tend[ind1]
amb_count = sex_amb['sex-count'].sum()
print(sex_amb)
sex name fold
0 1 承憲 9
1 1 均平 7
2 0 思安 6
3 1 佑誠 3
4 0 乃馨 0
... ... ... ...
10725 1 嘉銘 3
10726 0 佳芸 8
10727 0 又華 3
10728 1 子晉 0
10729 0 芸靜 2
[10730 rows x 3 columns]
name- sex-mean sex-count
6777 育瑋 0.5 4
338 以恩 0.5 4
7783 郁軒 0.5 4
2513 宜謙 0.5 4
5920 祐嘉 0.5 4
... ... ... ...
397 伊華 0.5 2
7725 郁 0.5 2
3808 捷 0.5 2
7747 郁棋 0.5 2
7456 詠綸 0.5 2
[63 rows x 3 columns]
#先篩選出不同功能的資料集
import numpy as np
from sklearn.metrics import f1_score
from sklearn.linear_model import LogisticRegression
train_name_df = name_df.loc[name_df['fold'] <= 6]
valid_name_df = name_df.loc[name_df['fold'] == 7 ]
stack_name_df = name_df.loc[name_df['fold'] == 8 ]
test_name_df = name_df.loc[name_df['fold'] == 9 ]
def select_feature(name, length):
feature = []
for i in range(length):
if len(name[i]) ==1 :
feature.append(name[i])
else:
feature.append(name[i])
feature.append(name[i][0])
feature.append(name[i][1])
feature = pd.value_counts(feature)
feature = feature.loc[feature >1 ]
return feature.index
def one_hot_encoding(name, length, datas):
x_data= np.zeros((length, len(datas)))
for i in range(length):
if len(name[i]) == 1:
sim = 0
for j in range(len(datas)):
if name[i] == datas[j]:
x_data[i][j] == 1
sim += 1
if sim == 0:
x_data[i][-1] == 1
else:
for k in range(3):
if k ==0:
sim = 0
for j in range(len(datas)):
if name[i] == datas[j]:
x_data[i][j] = 1
sim += 1
if sim == 0:
x_data[i][-1] = 1
elif k ==1:
sim = 0
for j in range(len(datas)):
if name[i][0] == datas[j]:
x_data[i][j] = 1
sim += 1
if sim == 0:
x_data[i][-1] = 1
elif k ==2:
sim = 0
for j in range(len(datas)):
if name[i][1] == datas[j]:
x_data[i][j] = 1
sim += 1
if sim == 0:
x_data[i][-1] = 1
return x_data
data = select_feature(train_name_df['name'].values,len(train_name_df['name'].values))
data = data.tolist()
data.append('Other_Feature_')
X_train = one_hot_encoding(train_name_df['name'].values, len(train_name_df['name'].values), data)
X_valid = one_hot_encoding(valid_name_df['name'].values, len(valid_name_df['name'].values), data)
X_stack = one_hot_encoding(stack_name_df['name'].values, len(stack_name_df['name'].values), data)
X_test = one_hot_encoding(test_name_df['name'].values, len(test_name_df['name'].values), data)
y_train = train_name_df['sex'].values
y_valid = valid_name_df['sex'].values
y_stack = stack_name_df['sex'].values
y_test = test_name_df['sex'].values
print(f'X_train:{X_train.shape},y_train:{y_train.shape}, X_valid:{X_valid.shape}, y_valid:{y_valid.shape},X_stack:{X_stack.shape},y_stack:{y_stack.shape}, X_test:{X_test.shape},y_test:{y_test.shape}')
X_train:(7483, 1630),y_train:(7483,), X_valid:(1110, 1630), y_valid:(1110,),X_stack:(1073, 1630),y_stack:(1073,), X_test:(1064, 1630),y_test:(1064,)
grid_c = []
f1_result = []
accuracy = []
bestc = 0
bestf1 = 0
grid_c = np.logspace(-4, 3, base = 10, num=20)
for i in range(20):
logic5 = LogisticRegression(penalty = 'l2', max_iter = 1000, C=grid_c[i])
logic5.fit(X_train, y_train)
ypred = logic5.predict(X_valid)
my = y_valid.shape[0]
correct = 0
for j in range(my):
if y_valid[j] == ypred[j]:
correct += 1
accuracy1= correct/my
accuracy.append(accuracy1)
f1_result.append(f1_score(y_valid, ypred))
if f1_score(y_valid, ypred) > bestf1:
bestf1 = f1_score(y_valid, ypred)
bestc = grid_c[i]
print(bestc)
183.29807108324337
from sklearn import metrics
X_trainvalid = np.concatenate((X_train, X_valid))
y_trainvalid = np.concatenate((y_train, y_valid))
logic6 = LogisticRegression(penalty = 'l2', max_iter = 1000, C=bestc)
logic6.fit(X_trainvalid, y_trainvalid)
ypred = logic6.predict(X_test)
highindex = np.argsort(np.absolute(logic6.coef_))[0][-20:]
highindex = highindex.tolist()
highindex = list(reversed(highindex))
print(metrics.classification_report(y_test, ypred),highindex)
top20_data=[]
top20_coef = []
for i in range(len(highindex)):
top20_data.append(data[highindex[i]])
top20_coef.append(logic6.coef_[0][highindex[i]])
pd.DataFrame(data=top20_coef, index=top20_data).head(20).T
precision recall f1-score support
0 0.91 0.86 0.88 577
1 0.84 0.90 0.87 487
accuracy 0.88 1064
macro avg 0.88 0.88 0.88 1064
weighted avg 0.88 0.88 0.88 1064
[83, 567, 462, 340, 489, 313, 1021, 147, 17, 179, 191, 302, 10, 48, 1403, 486, 537, 409, 321, 90]
| 傑 | 森 | 鋒 | 玲 | 凌 | 美 | 嵐 | 雯 | 婷 | 卉 | 薇 | 綾 | 萱 | 婕 | 絃 | 顥 | 幼 | 松 | 展 | 潔 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 11.378408 | 10.548896 | 10.503279 | -10.183509 | -9.876388 | -9.848239 | -9.824687 | -9.79773 | -9.748038 | -9.671069 | -9.662506 | -9.639585 | -9.528893 | -9.395125 | -9.268145 | 9.260534 | -9.224704 | 9.10784 | 9.020447 | -8.995233 |
from sklearn.ensemble import RandomForestClassifier
import math
grid_est = []
f1_result = []
best_nest = 0
bestf1 = 0
grid_est = np.logspace(math.log(5,10), 3, base = 10,num=10)
for i in range(10):
grid_est[i] = int(round(grid_est[i]))
grid_est = grid_est.tolist()
for i in range(10):
grid_est[i] = int(grid_est[i])
for i in range(10):
clf = RandomForestClassifier(n_estimators=grid_est[i])
clf.fit(X_train, y_train)
ypred = clf.predict(X_valid)
my = y_valid.shape[0]
correct = 0
f1_result.append(f1_score(y_valid, ypred))
if f1_score(y_valid, ypred) > bestf1:
bestf1 = f1_score(y_valid, ypred)
best_nest = grid_est[i]
print(f'best_nest:{best_nest}')
best_nest:5
clf2 = RandomForestClassifier(n_estimators = best_nest)
clf2.fit(X_trainvalid, y_trainvalid)
ypred = clf2.predict(X_test)
importance = clf2.feature_importances_
highindex = np.argsort(np.absolute(importance))[-20:]
print(highindex)
highindex = highindex.tolist()
highindex = list(reversed(highindex))
print(metrics.classification_report(y_test, ypred))
top20_data=[]
top20_coef = []
for i in range(len(highindex)):
top20_data.append(data[highindex[i]])
top20_coef.append(importance[highindex[i]])
pd.DataFrame(data=top20_coef, index=top20_data).head(20).T
[ 4 50 25 40 6 54 52 34 39 29 23 27 7 16 42 5 8 10 17 2]
precision recall f1-score support
0 0.86 0.81 0.84 577
1 0.79 0.85 0.82 487
accuracy 0.83 1064
macro avg 0.83 0.83 0.83 1064
weighted avg 0.83 0.83 0.83 1064
| 妤 | 婷 | 萱 | 翔 | 柏 | 柔 | 承 | 佳 | 蓁 | 怡 | 哲 | 雅 | 芷 | 晴 | 慈 | 宜 | 芸 | 瑄 | 涵 | 庭 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.018221 | 0.014982 | 0.014653 | 0.014291 | 0.012938 | 0.010144 | 0.010016 | 0.009977 | 0.009728 | 0.009726 | 0.009531 | 0.008841 | 0.008436 | 0.008404 | 0.008 | 0.007787 | 0.007759 | 0.007596 | 0.007559 | 0.007051 |
from sklearn.ensemble import GradientBoostingClassifier
f1score = []
clf3 = GradientBoostingClassifier(n_estimators=1500, learning_rate=0.1, max_depth=1, random_state=0)
clf3.fit(X_train, y_train)
ypred = clf3.predict(X_valid)
beststage1 = 0
bestf1score1 = 0
stage = 1
for i in clf3.staged_predict(X_valid):
f1score.append(f1_score(y_valid, i))
if f1_score(y_valid, i) > bestf1score1:
beststage1 = stage
bestf1score1 = f1_score(y_valid, i)
stage += 1
print(bestf1score1, beststage1)
0.8762243989314337 1471
from sklearn.ensemble import GradientBoostingClassifier
f1score2 = []
clf3 = GradientBoostingClassifier(n_estimators=1500, learning_rate=0.5, max_depth=1, random_state=0)
clf3.fit(X_train, y_train)
ypred = clf3.predict(X_valid)
beststage2 = 0
bestf1score2 = 0
stage = 0
for i in clf3.staged_predict(X_valid):
f1score2.append(f1_score(y_valid, i))
if f1_score(y_valid, i) > bestf1score2:
beststage2 = stage
bestf1score2 = f1_score(y_valid, i)
stage += 1
print(bestf1score2, beststage2)
0.9044117647058824 832
from sklearn.ensemble import GradientBoostingClassifier
f1score3 = []
clf3 = GradientBoostingClassifier(n_estimators=1500, learning_rate=1, max_depth=1, random_state=0)
clf3.fit(X_train, y_train)
ypred = clf3.predict(X_valid)
beststage3 = 0
bestf1score3 = 0
stage = 1
for i in clf3.staged_predict(X_valid):
f1score3.append(f1_score(y_valid, i))
if f1_score(y_valid, i)>bestf1score3:
beststage3= stage
bestf1score3 = f1_score(y_valid, i)
stage+=1
print(bestf1score3, beststage3)
0.8830188679245283 424
a=list(range(1,1501))
import matplotlib.pyplot as plt
plt.plot(a, f1score,'r-',label = 'lr0.1')
plt.plot(a, f1score2,'b-',label = 'lr0.5')
plt.plot(a, f1score3,'g-', label = 'lr1')
plt.title('f1 score for different learning rate')
plt.xlabel('stages')
plt.ylabel('f1 score')
plt.legend()
<matplotlib.legend.Legend at 0x2d1838a7eb0>
clf3 = GradientBoostingClassifier(n_estimators=beststage2, learning_rate=0.5, max_depth=1, random_state=0)
clf3.fit(X_trainvalid, y_trainvalid)
ypred = clf3.predict(X_test)
importance = clf3.feature_importances_
highindex = np.argsort(np.absolute(importance))[-20:]
print(highindex)
highindex = highindex.tolist()
highindex = list(reversed(highindex))
print(metrics.classification_report(y_test, ypred))
top20_data=[]
top20_coef = []
for i in range(len(highindex)):
top20_data.append(data[highindex[i]])
top20_coef.append(importance[highindex[i]])
pd.DataFrame(data=top20_coef, index=top20_data).head(20).T
[48 18 54 6 50 40 52 34 7 39 42 23 27 29 16 17 5 10 8 2]
precision recall f1-score support
0 0.92 0.84 0.88 577
1 0.82 0.92 0.87 487
accuracy 0.87 1064
macro avg 0.87 0.88 0.87 1064
weighted avg 0.88 0.87 0.87 1064
| 妤 | 翔 | 萱 | 柏 | 婷 | 承 | 哲 | 蓁 | 怡 | 柔 | 雅 | 佳 | 芷 | 晴 | 芸 | 涵 | 宜 | 慈 | 瑜 | 婕 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.030279 | 0.02323 | 0.020647 | 0.020014 | 0.018889 | 0.013559 | 0.013367 | 0.012673 | 0.012113 | 0.011683 | 0.011326 | 0.011299 | 0.011261 | 0.010998 | 0.010951 | 0.010915 | 0.010634 | 0.010494 | 0.010094 | 0.009637 |
proba1 = logic6.predict_proba(X_stack)
proba1 = np.delete(proba1, 0, axis = 1)
probatest1 = logic6.predict_proba(X_test)
probatest1 = np.delete(probatest1, 0, axis = 1)
proba2 = clf2.predict_proba(X_stack)
proba2 = np.delete(proba2, 0, axis = 1)
probatest2 = clf2.predict_proba(X_test)
probatest2 = np.delete(probatest2, 0, axis = 1)
proba3 = clf3.predict_proba(X_stack)
proba3 = np.delete(proba3, 0, axis = 1)
probatest3 = clf3.predict_proba(X_test)
probatest3 = np.delete(probatest3, 0, axis = 1)
logicstacking = LogisticRegression(penalty = 'none', max_iter = 1000)
x_new = np.concatenate((proba1,proba2,proba3), axis = 1)
x_newtest = np.concatenate((probatest1,probatest2,probatest3), axis = 1)
logicstacking.fit(x_new, y_stack)
highindex = logicstacking.coef_.T
highindex = highindex.tolist()
coef = ['logistic', 'random forest', 'GDBT']
ypred = logicstacking.predict(x_newtest)
print(metrics.classification_report(y_test, ypred))
pd.DataFrame(data=highindex, index=coef).T
precision recall f1-score support
0 0.91 0.85 0.88 577
1 0.84 0.90 0.87 487
accuracy 0.88 1064
macro avg 0.88 0.88 0.88 1064
weighted avg 0.88 0.88 0.88 1064
| logistic | random forest | GDBT | |
|---|---|---|---|
| 0 | 2.274069 | 0.056796 | 5.592238 |
# 資料前處理
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
stu_adm = pd.read_csv('ds/student_admission106.csv', encoding="utf-8", dtype=str)
uname = pd.read_csv('ds/univ_name106short1.csv', encoding="utf-8", dtype=str)
all_depid = stu_adm['department_id'].unique()
all_stuid = stu_adm['student_id'].unique()
ndepid = all_depid.shape[0]
nstuid = all_stuid.shape[0]
print("There are %d students and %d departments in total." % (nstuid, ndepid))
print("offers received by students:")
stu_adm.head(10)
%matplotlib inline
import numpy as np
import pandas as pd
stu_adm = pd.read_csv('ds/student_admission106.csv', encoding="utf-8", dtype=str)
uname = pd.read_csv('ds/univ_name106short1.csv', encoding="utf-8", dtype=str)
all_depid = stu_adm['department_id'].unique()
all_stuid = stu_adm['student_id'].unique()
ndepid = all_depid.shape[0]
nstuid = all_stuid.shape[0]
print("In raw data, there are %d students and %d departments in total." % (nstuid, ndepid))
#construct the department-student matrix (i.e. array).
dep_stu = np.zeros((ndepid, nstuid))
rowname = all_depid.copy()
depid_seq_map = dict()
for i in range(ndepid):
depid_seq_map[all_depid[i]] = i
stuid_seq_map = dict()
for i in range(nstuid):
stuid_seq_map[all_stuid[i]] = i
for cindex, row in stu_adm.iterrows():
#print(cindex, row)
dep_seq = depid_seq_map[row['department_id']]
stu_seq = stuid_seq_map[row['student_id']]
#print(dep_seq, stu_seq)
dep_stu[dep_seq, stu_seq] = 1
#Remove very small departments.
min_stu_per_dep = 10
min_apply_dep_per_stu = 2
#remove small departments and single-application students.
dep_apply_sum = np.sum(dep_stu, axis = 1)
keeprow = dep_apply_sum >= min_stu_per_dep
rowname = rowname[keeprow]
dep_stu2 = dep_stu[keeprow,:]
stu_apply_sum = np.sum(dep_stu2, axis = 0)
dep_stu2 = dep_stu2[:, stu_apply_sum >= min_apply_dep_per_stu]
#another run of filtering
dep_apply_sum = np.sum(dep_stu2, axis = 1)
dep_stu2 = dep_stu2[dep_apply_sum >= min_stu_per_dep,:]
rowname = rowname[dep_apply_sum >= min_stu_per_dep]
stu_apply_sum = np.sum(dep_stu2, axis = 0)
dep_stu2 = dep_stu2[:, stu_apply_sum >= min_apply_dep_per_stu]
#third run of filtering
dep_apply_sum = np.sum(dep_stu2, axis = 1)
dep_stu2 = dep_stu2[dep_apply_sum >= min_stu_per_dep,:]
rowname = rowname[dep_apply_sum >= min_stu_per_dep]
stu_apply_sum = np.sum(dep_stu2, axis = 0)
dep_stu2 = dep_stu2[:, stu_apply_sum >= min_apply_dep_per_stu]
#check to make sure the two conditions are satisfied.
dep_apply_sum = np.sum(dep_stu2, axis = 1)
print("Number of department too small:", np.sum(dep_apply_sum < min_stu_per_dep))
stu_apply_sum = np.sum(dep_stu2, axis = 0)
print("Number of students applying only one department:", np.sum(stu_apply_sum <min_apply_dep_per_stu))
#now both conditions are satisfied.
uname['depname'] = uname.school_name_abbr + uname.department_name_abbr
uname2 = uname[['department_id', 'depname', 'category_name']].copy()
#this is for later use, to color data points.
category_id, category_levels = pd.factorize(uname2.category_name)
#uname2['category_id'] = category_id / np.max(category_id)
uname2['category_id'] = category_id
category_id.shape
#create a data frame for column name
colname_df = pd.DataFrame({'department_id': rowname})
colname_df = colname_df.merge(uname2, how = "left", on="department_id")
topdepid = np.argsort(dep_apply_sum)[::-1]
topn = 10
topdep = pd.DataFrame({'department_id': rowname[topdepid[0:topn]],
'department_name': colname_df.depname.values[topdepid[0:topn]],
'num_applicant': dep_apply_sum[topdepid[0:topn]]
})
topdep
num_dep, num_stu = dep_stu2.shape
There are 60461 students and 1976 departments in total. offers received by students: In raw data, there are 60461 students and 1976 departments in total. Number of department too small: 0 Number of students applying only one department: 0
for i in range(11):
print(colname_df[colname_df['category_id']==i])
department_id depname category_name category_id
60 002012 臺師教育 教育 0
62 002032 臺師社會教育 教育 0
63 002042 臺師健康衛生 教育 0
64 002052 臺師人類家庭生活 教育 0
65 002062 臺師人類家庭幼兒 教育 0
... ... ... ... ...
1738 036042 屏東教育輔導 教育 0
1778 041282 中正成人教育 教育 0
1849 059112 南華幼兒教育 教育 0
1855 100042 嘉義幼兒教育 教育 0
1886 058132 暨南國際文教 教育 0
[87 rows x 4 columns]
department_id depname category_name category_id
0 001012 臺大中文 藝術及人文 1
1 001022 臺大外文 藝術及人文 1
2 001032 臺大歷史 藝術及人文 1
3 001042 臺大哲學 藝術及人文 1
4 001052 臺大人類學系 藝術及人文 1
... ... ... ... ...
1893 130122 佛光外文 藝術及人文 1
1902 133102 明道時尚造形 藝術及人文 1
1904 133122 明道中文學 藝術及人文 1
1905 133132 明道應用英語 藝術及人文 1
1906 133142 明道應用日語 藝術及人文 1
[367 rows x 4 columns]
department_id depname category_name category_id
5 001062 臺大圖書資訊 社會科學、新聞學及圖書資訊 2
12 001132 臺大心理 社會科學、新聞學及圖書資訊 2
13 001142 臺大地理環境 社會科學、新聞學及圖書資訊 2
15 001162 臺大政治理論 社會科學、新聞學及圖書資訊 2
16 001172 臺大政治國際關係 社會科學、新聞學及圖書資訊 2
... ... ... ... ...
1843 056022 臺藝廣播電視 社會科學、新聞學及圖書資訊 2
1851 099122 臺北經濟 社會科學、新聞學及圖書資訊 2
1852 099132 臺北社會 社會科學、新聞學及圖書資訊 2
1894 130132 佛光社會 社會科學、新聞學及圖書資訊 2
1895 130142 佛光心理 社會科學、新聞學及圖書資訊 2
[149 rows x 4 columns]
department_id depname category_name category_id
45 001462 臺大工商管理企管 商業、管理及法律 3
46 001472 臺大工商管理科管 商業、管理及法律 3
47 001482 臺大會計 商業、管理及法律 3
48 001492 臺大財金 商業、管理及法律 3
49 001502 臺大國企 商業、管理及法律 3
... ... ... ... ...
1883 051072 長榮會計資訊 商業、管理及法律 3
1887 059042 南華文創管理行銷 商業、管理及法律 3
1896 130152 佛光公共國際兩岸 商業、管理及法律 3
1897 130162 佛光公共政策行政 商業、管理及法律 3
1909 134352 亞洲財金科技 商業、管理及法律 3
[316 rows x 4 columns]
department_id depname category_name category_id
8 001092 臺大數學 自然科學、數學及統計 4
9 001102 臺大物理 自然科學、數學及統計 4
10 001112 臺大化學 自然科學、數學及統計 4
11 001122 臺大地質科學 自然科學、數學及統計 4
14 001152 臺大大氣 自然科學、數學及統計 4
... ... ... ... ...
1723 023092 彰師物理光電 自然科學、數學及統計 4
1743 038132 臺東應科奈米 自然科學、數學及統計 4
1744 038142 臺東應科應物 自然科學、數學及統計 4
1787 042332 大葉生物產業(食品) 自然科學、數學及統計 4
1808 046422 銘傳生科(桃園) 自然科學、數學及統計 4
[211 rows x 4 columns]
department_id depname category_name category_id
50 001512 臺大資管 資訊通訊科技 5
53 001542 臺大資工 資訊通訊科技 5
100 003062 中興資管 資訊通訊科技 5
109 003152 中興資科工程 資訊通訊科技 5
173 004392 成大資工 資訊通訊科技 5
... ... ... ... ...
1876 050332 實踐資科通訊App(高雄) 資訊通訊科技 5
1877 050342 實踐資科通訊多媒體(高雄) 資訊通訊科技 5
1878 050352 實踐資科通訊智慧機器(高雄) 資訊通訊科技 5
1890 130092 佛光資應學習數位 資訊通訊科技 5
1900 133072 明道資訊傳播 資訊通訊科技 5
[118 rows x 4 columns]
department_id depname category_name category_id
28 001292 臺大土木 工程、製造及營建 6
29 001302 臺大機械工程學 工程、製造及營建 6
30 001312 臺大化工 工程、製造及營建 6
31 001322 臺大工科海洋 工程、製造及營建 6
32 001332 臺大材料科學與工程 工程、製造及營建 6
... ... ... ... ...
1903 133112 明道景觀環境 工程、製造及營建 6
1913 150132 宜蘭電機 工程、製造及營建 6
1914 150142 宜蘭電子工程 工程、製造及營建 6
1915 151012 聯合機械工程學 工程、製造及營建 6
1916 151022 聯合化工 工程、製造及營建 6
[309 rows x 4 columns]
department_id depname category_name category_id
20 001212 臺大社會工作 醫藥衛生及社會福利 7
21 001222 臺大醫學 醫藥衛生及社會福利 7
22 001232 臺大牙醫 醫藥衛生及社會福利 7
23 001242 臺大藥學 醫藥衛生及社會福利 7
24 001252 臺大醫檢暨生技 醫藥衛生及社會福利 7
... ... ... ... ...
1734 035182 北市大衛生福利 醫藥衛生及社會福利 7
1853 099142 臺北社會工作 醫藥衛生及社會福利 7
1871 152012 馬偕醫學 醫藥衛生及社會福利 7
1872 152022 馬偕護理學 醫藥衛生及社會福利 7
1907 134012 亞洲健康產管健康產管 醫藥衛生及社會福利 7
[164 rows x 4 columns]
department_id depname category_name category_id
90 002322 臺師不分系(晨光) 其他 8
132 003382 中興興翼A 其他 8
133 003392 中興興翼B 其他 8
134 003402 中興興翼C 其他 8
179 004452 成大大一不分系 其他 8
181 004482 成大成星招生甲(文社) 其他 8
182 004492 成大成星招生乙(管理) 其他 8
183 004512 成大成星招生丁(工) 其他 8
184 004522 成大成星招生戊(生醫) 其他 8
244 006392 政大不分系(政星) 其他 8
266 007232 高醫不分系(薪B) 其他 8
267 007242 高醫不分系(薪C) 其他 8
388 011402 清大清華學院丙(創新) 其他 8
389 011412 清大清華學院丁(領導) 其他 8
390 011422 清大清華學院戊(跨領域) 其他 8
391 011432 清大旭日甲(人文) 其他 8
392 011442 清大旭日乙(理工) 其他 8
393 011452 清大旭日丙(電資) 其他 8
394 011482 清大清華學院乙(美術) 其他 8
427 013142 交大理學院學士(乙) 其他 8
428 013152 交大理學院學士(丙) 其他 8
429 013162 交大理學院學士(丁) 其他 8
443 013302 交大旋坤揚帆甲(電機) 其他 8
444 013312 交大旋坤揚帆乙(工程) 其他 8
445 013322 交大旋坤揚帆丙(理學) 其他 8
446 013342 交大旋坤揚帆戊(人社) 其他 8
565 016262 中央向日葵聯招甲 其他 8
566 016272 中央向日葵聯招乙 其他 8
790 025132 陽明不分系(璞A) 其他 8
1306 051632 長榮東南亞觀光 其他 8
1307 051642 長榮東南亞產業商貿 其他 8
1437 099212 臺北飛鳶組 其他 8
1870 112062 康寧企管(臺南) 其他 8
department_id depname category_name category_id
33 001342 臺大農藝 農業、林業、漁業及獸醫 9
35 001362 臺大農業化學 農業、林業、漁業及獸醫 9
36 001372 臺大森林環境資源 農業、林業、漁業及獸醫 9
37 001382 臺大動物科學技術 農業、林業、漁業及獸醫 9
38 001392 臺大農業經濟 農業、林業、漁業及獸醫 9
39 001402 臺大園藝景觀 農業、林業、漁業及獸醫 9
40 001412 臺大獸醫 農業、林業、漁業及獸醫 9
41 001422 臺大生物產業傳播 農業、林業、漁業及獸醫 9
44 001452 臺大植物微生物學 農業、林業、漁業及獸醫 9
119 003252 中興農藝 農業、林業、漁業及獸醫 9
120 003262 中興園藝 農業、林業、漁業及獸醫 9
121 003272 中興森林學林學 農業、林業、漁業及獸醫 9
122 003282 中興森林木材 農業、林業、漁業及獸醫 9
123 003292 中興植物病理學 農業、林業、漁業及獸醫 9
125 003312 中興動物科學 農業、林業、漁業及獸醫 9
126 003322 中興土壤環境 農業、林業、漁業及獸醫 9
129 003352 中興國際農企 農業、林業、漁業及獸醫 9
131 003372 中興獸醫 農業、林業、漁業及獸醫 9
343 009402 東海畜產生物 農業、林業、漁業及獸醫 9
591 017262 文化園藝生物 農業、林業、漁業及獸醫 9
592 017272 文化動物科學 農業、林業、漁業及獸醫 9
593 017282 文化森林保育 農業、林業、漁業及獸醫 9
742 021092 海洋水產養殖 農業、林業、漁業及獸醫 9
748 021152 海洋環境生物漁業 農業、林業、漁業及獸醫 9
1449 100162 嘉義農藝 農業、林業、漁業及獸醫 9
1450 100172 嘉義園藝 農業、林業、漁業及獸醫 9
1451 100182 嘉義森林資源 農業、林業、漁業及獸醫 9
1452 100192 嘉義木質設計 農業、林業、漁業及獸醫 9
1453 100232 嘉義植物醫學 農業、林業、漁業及獸醫 9
1466 100372 嘉義獸醫 農業、林業、漁業及獸醫 9
1859 100202 嘉義動物科學 農業、林業、漁業及獸醫 9
1860 100212 嘉義生物農業 農業、林業、漁業及獸醫 9
1899 133062 明道精緻農業 農業、林業、漁業及獸醫 9
1910 150102 宜蘭生物技術動科 農業、林業、漁業及獸醫 9
1911 150112 宜蘭森林資源 農業、林業、漁業及獸醫 9
1912 150122 宜蘭園藝 農業、林業、漁業及獸醫 9
department_id depname category_name category_id
158 004242 成大交通管理 服務 10
345 009422 東海餐管 服務 10
438 013252 交大運輸物管 服務 10
470 014242 淡江運輸管理 服務 10
497 014512 淡江國際觀光(蘭陽) 服務 10
... ... ... ... ...
1879 050422 實踐休閒文化(高雄) 服務 10
1880 050432 實踐休閒戶外運動(高雄) 服務 10
1885 058122 暨南觀光餐旅餐管 服務 10
1898 133052 明道休閒保健 服務 10
1908 134312 亞洲休閒旅遊 服務 10
[127 rows x 4 columns]
realcategory = {0:'教育', 1:'藝術及人文',2:'社會科學、新聞學及圖書資訊',3:'商業、管理及法律',4:'自然科學、數學及統計', 5:'資訊通訊科技', 6:'工程、製造及營建', 7:'醫藥衛生及社會福利', 8:'其他', 9:'農業、林業、漁業及獸醫', 10:'服務'}
pd.DataFrame([realcategory]).head()
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 教育 | 藝術及人文 | 社會科學、新聞學及圖書資訊 | 商業、管理及法律 | 自然科學、數學及統計 | 資訊通訊科技 | 工程、製造及營建 | 醫藥衛生及社會福利 | 其他 | 農業、林業、漁業及獸醫 | 服務 |
for i in range(11):
cate = realcategory[i]
aa = colname_df[colname_df['category_id']==i]
print(f'{i}{cate}: {aa.shape[0]}')
0教育: 87 1藝術及人文: 367 2社會科學、新聞學及圖書資訊: 149 3商業、管理及法律: 316 4自然科學、數學及統計: 211 5資訊通訊科技: 118 6工程、製造及營建: 309 7醫藥衛生及社會福利: 164 8其他: 33 9農業、林業、漁業及獸醫: 36 10服務: 127
from sklearn.decomposition import PCA
pca = PCA(n_components=8)
X_new = pca.fit_transform(dep_stu2)
plt.figure(figsize = (20, 100))
d = 0
for i in range(8):
for j in range(8):
if i<j:
d += 1
plt.subplot(18, 3, d)
plt.scatter(X_new[:, i], X_new[:, j], c=colname_df.category_id ,edgecolor='none', alpha=0.9, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title(f'pair {i} and {j}')
plt.colorbar()
# 3&6
from sklearn.manifold import MDS
from sklearn.preprocessing import MinMaxScaler
# 資料標準化
scaler = MinMaxScaler()
dep_stu3 = scaler.fit_transform(dep_stu2)
embedding = MDS(n_components=2)
X_new= embedding.fit_transform(dep_stu3)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("MDS metrics")
plt.colorbar()
# mds的原則是保持“距離”不變
<matplotlib.colorbar.Colorbar at 0x17b82100dc0>
embedding = MDS(n_components=2, metric=False)
X_new= embedding.fit_transform(dep_stu3)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("MDS non-metrics")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x17b82199eb0>
from sklearn.manifold import LocallyLinearEmbedding
LLE = LocallyLinearEmbedding(n_neighbors=20, n_components=2)
LLE2 = LocallyLinearEmbedding(n_neighbors=40, n_components=2)
X_new= LLE.fit_transform(dep_stu2)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("LLE 20_neighbors")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x17b7ba7e700>
X_new= LLE2.fit_transform(dep_stu2)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("LLE 40_neighbors")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x17b7c0a8f40>
from sklearn.decomposition import PCA
pca = PCA(n_components=100)
dep_stu4 = pca.fit_transform(dep_stu2)
LLE3 = LocallyLinearEmbedding(n_neighbors=20, n_components=2)
X_new= LLE3.fit_transform(dep_stu4)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("LLE 20_neighbors 100comp")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x17b83969c70>
from sklearn.decomposition import KernelPCA
kPCA = KernelPCA(n_components=8, kernel='rbf')
X_new= kPCA.fit_transform(dep_stu2)
plt.scatter(X_new[:, 3], X_new[:, 6], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("RBF kernal_PCA ")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x17b83b89d30>
kPCA = KernelPCA(n_components=8, kernel='cosine')
X_new= kPCA.fit_transform(dep_stu2)
plt.scatter(X_new[:, 3], X_new[:, 6], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("cosine kernal_PCA ")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x17b83a22a30>
kPCA = KernelPCA(n_components=8, kernel='sigmoid')
X_new= kPCA.fit_transform(dep_stu2)
plt.scatter(X_new[:, 3], X_new[:, 6], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("sigmoid kernal_PCA ")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x17b8740df10>
from sklearn.manifold import TSNE
X_new = TSNE(n_components=2,random_state = np.random.RandomState(0) , perplexity=20).fit_transform(dep_stu2)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("tSNE Euclidian")
plt.colorbar()
c:\Users\User\anaconda3\lib\site-packages\sklearn\manifold\_t_sne.py:800: FutureWarning: The default initialization in TSNE will change from 'random' to 'pca' in 1.2. warnings.warn( c:\Users\User\anaconda3\lib\site-packages\sklearn\manifold\_t_sne.py:810: FutureWarning: The default learning rate in TSNE will change from 200.0 to 'auto' in 1.2. warnings.warn(
<matplotlib.colorbar.Colorbar at 0x14843e8f190>
plt.grid()
X_new = TSNE(n_components=2,random_state = np.random.RandomState(0) ,metric='cosine', perplexity=20).fit_transform(dep_stu2)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("tSNE Cosine")
plt.colorbar()
c:\Users\User\anaconda3\lib\site-packages\sklearn\manifold\_t_sne.py:800: FutureWarning: The default initialization in TSNE will change from 'random' to 'pca' in 1.2. warnings.warn( c:\Users\User\anaconda3\lib\site-packages\sklearn\manifold\_t_sne.py:810: FutureWarning: The default learning rate in TSNE will change from 200.0 to 'auto' in 1.2. warnings.warn(
<matplotlib.colorbar.Colorbar at 0x14847f4c580>
X_new = TSNE(n_components=2,random_state = np.random.RandomState(0), metric = 'jaccard', perplexity=20).fit_transform(dep_stu2)
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.title("tSNE jaccard")
plt.colorbar()
c:\Users\User\anaconda3\lib\site-packages\sklearn\manifold\_t_sne.py:800: FutureWarning: The default initialization in TSNE will change from 'random' to 'pca' in 1.2. warnings.warn( c:\Users\User\anaconda3\lib\site-packages\sklearn\manifold\_t_sne.py:810: FutureWarning: The default learning rate in TSNE will change from 200.0 to 'auto' in 1.2. warnings.warn( c:\Users\User\anaconda3\lib\site-packages\sklearn\metrics\pairwise.py:2008: DataConversionWarning: Data was converted to boolean for metric jaccard warnings.warn(msg, DataConversionWarning)
<matplotlib.colorbar.Colorbar at 0x24150937970>
X_new = TSNE(n_components=2,early_exaggeration = 5,random_state = np.random.RandomState(0), learning_rate = 500, min_grad_norm = 1e-9, init='pca' ,metric = 'cosine', perplexity=35,angle = 0.2).fit_transform(dep_stu2)
c:\Users\User\anaconda3\lib\site-packages\sklearn\manifold\_t_sne.py:996: FutureWarning: The PCA initialization in TSNE will change to have the standard deviation of PC1 equal to 1e-4 in 1.2. This will ensure better convergence. warnings.warn(
want = colname_df.depname.tolist()
透過tSNE分配並增加Learning rate、提高threshold門檻、選擇cosine矩陣、增加perplexity等,輸出二維散布圖後可以發現有不錯的分配結果,如:各學校醫學系集中在散步圖右上角、圖片最下方主要是美術、設計及視覺藝術相關科系組成。
# 使中文字顯示在散布圖上
plt.rcParams['font.sans-serif'] = ['Taipei Sans TC Beta']
plt.figure(figsize = (500,330))
plt.scatter(X_new[:, 0], X_new[:, 1], c=colname_df.category_id ,edgecolor='none', alpha=0.7, cmap=plt.cm.get_cmap('Spectral', 11))
plt.axis('equal')
plt.grid()
plt.title("tSNE best")
for i, label in enumerate(want):
plt.annotate(label, (X_new[:, 0][i], X_new[:, 1][i]))
plt.colorbar()
plt.savefig('fig_Q2.6_best2.png')